/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xpath;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author Rishav
 */
class WorkerThread implements Runnable {

    private String command;
    private final int time;

    public WorkerThread(String s, int time) {

        this.command = s;
        this.time = time;

    }

    @Override

    public void run() {

        System.out.println(System.nanoTime()+" Start. Command = " + command+" time="+(10-time));

        processCommand();

        System.out.println(System.nanoTime()+" End. Command = " + command+" time="+(10-time));

    }

    private void processCommand() {

        try {
            
            System.out.println(System.nanoTime()+" Processing " + command);
            Thread.sleep((10-time)*1000);
        
        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    @Override

    public String toString() {

        return this.command;

    }
}

public class ThreadDemo {

    public static void main(String args[]) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {

            Runnable worker = new WorkerThread("" + i, i);

            executor.execute(worker);

        }

        executor.shutdown();

        while (!executor.isTerminated()) {
        }

        System.out.println("Finished all threads in "+(System.currentTimeMillis()-start));
    }
}
